package cn.doctor.assistant.pad.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import cn.doctor.assistant.pad.ui.UI;

public class PopMenu implements View.OnClickListener {

    private Context mContext;
    private PopupWindow mPopup;
    private View actionTarget;
    private View contentView;

    //actionTarget 是点击按键.
    public PopMenu(View actionTarget, int resLayoutId) {
        this.actionTarget = actionTarget;
        mContext = actionTarget.getContext();
        contentView = LayoutInflater.from(mContext).inflate(resLayoutId, null);
        mPopup = new PopupWindow(contentView, UI.dip2px(100), ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopup.setFocusable(true);
        mPopup.setOutsideTouchable(true);
        setOnClickListener();
    }

    public PopMenu(View actionTarget, View contentView) {
        this.actionTarget = actionTarget;
        this.contentView = contentView;
        mContext = actionTarget.getContext();
        mPopup = new PopupWindow(contentView, UI.dip2px(100), ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopup.setFocusable(true);
        mPopup.setOutsideTouchable(true);
        setOnClickListener();
    }

    private View.OnClickListener mListener = null;
    public void setOnItemClickListener(View.OnClickListener l) {
        this.mListener = l;
    }

    //设置子view被点击的事件.
    private void setOnClickListener() {
        //this.mClickListener = l;
        if (contentView instanceof ViewGroup) {
            int count = ((ViewGroup) contentView).getChildCount();
            for (int i = 0; i < count; i++) {
                View child = ((ViewGroup) contentView).getChildAt(i);

                if (child.isClickable() && child.getId() != 0) {
                    child.setOnClickListener(this);
                }
            }
        } else {
            contentView.setOnClickListener(this);
        }
    }

    public void show() {
        if (!mPopup.isShowing()) {
            mPopup.showAsDropDown(actionTarget, 3, 3);
        }
    }

    public void dismiss() {
        if (mPopup.isShowing()) {
            mPopup.dismiss();
        }
    }

    private int clickedId = 0;
    public int getSelectedId() {
        return clickedId;
    }

    @Override
    public void onClick(View v) {
        clickedId = v.getId();
        if (mListener != null) {
            mListener.onClick(v);
        }
    }
}
